const express = require('express');
const router = express.Router();
const User = require('../models/User');

// Send friend request
router.post('/request', async (req, res) => {
  try {
    console.log("收到好友申请请求:", req.body);
    const { fromId, toId } = req.body;

    // 验证参数
    if (!fromId || !toId) {
      return res.status(400).json({ message: '缺少必要参数' });
    }

    // 检查是否申请添加自己
    if (fromId === toId) {
      return res.status(400).json({ message: '不能添加自己为好友' });
    }

    // 检查用户是否存在
    const [fromUser, toUser] = await Promise.all([
      User.findOne({ userId: fromId }),
      User.findOne({ userId: toId })
    ]);

    if (!fromUser || !toUser) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 检查是否已经是好友
    if (fromUser.friends?.includes(toId)) {
      return res.status(400).json({ message: '已经是好友了' });
    }

    // 发送好友请求通知
    const io = req.app.get('io');
    if (!io) {
      console.error('Socket.IO 实例未找到');
      return res.status(500).json({ message: '服务器配置错误' });
    }

    console.log(`准备发送好友请求通知: ${fromUser.nickname} -> ${toUser.nickname}`);
    // Include avatar in request data
    io.to(toId).emit('friendRequest', {
      fromId,
      fromNickname: fromUser.nickname,
      avatar: fromUser.avatar // Add avatar to request data
    });
    console.log('好友请求通知已发送');

    res.json({ success: true });

  } catch (err) {
    console.error('处理好友请求失败:', err);
    res.status(500).json({ 
      message: '发送好友请求失败',
      error: err.message 
    });
  }
});

// Accept friend request
router.post('/accept', async (req, res) => {
  try {
    const { fromId, toId } = req.body;
    
    // Add to both users' friend lists
    const [fromUser, toUser] = await Promise.all([
      User.findOneAndUpdate(
        { userId: fromId },
        { $addToSet: { friends: toId } },
        { new: true }
      ),
      User.findOneAndUpdate(
        { userId: toId },
        { $addToSet: { friends: fromId } },
        { new: true }
      )
    ]);

    // Return updated friend info
    res.json({ 
      success: true,
      newFriend: {
        userId: fromId,
        nickname: fromUser.nickname,
        avatar: fromUser.avatar,
        online: true // We know they're online since they just sent the request
      }
    });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

router.post('/reject', async (req, res) => {
  const { fromId, toId } = req.body;
  // Notify rejection
  req.app.get('io').to(fromId).emit('friendRequestRejected', { 
    friendId: toId 
  });
  res.json({ success: true });
});

router.post('/set-remark', async (req, res) => {
  try {
    const { userId, friendId, remark } = req.body;

    const user = await User.findOne({ userId });
    const friendIndex = user.friends.findIndex(f => f.userId === friendId);
    
    if (friendIndex === -1) {
      return res.status(404).json({ message: '好友不存在' });
    }

    user.friends[friendIndex].remark = remark;
    await user.save();

    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ message: '设置备注失败' });
  }
});

router.get('/get-remark', async (req, res) => {
  try {
    const { userId, friendId } = req.query;

    const user = await User.findOne({ userId });
    const friend = user.friends.find(f => f.userId === friendId);

    if (!friend) {
      return res.status(404).json({ message: '好友不存在' });
    }

    res.json({ success: true, remark: friend.remark });
  } catch (error) {
    res.status(500).json({ message: '获取备注失败' });
  }
});

module.exports = router;